<?php

class Sponsor extends DataObject {
    private static $singular_name = "Sponsor";
    private static $plural_name = "Sponsors";
    
    private static $root_username = 'root';
    
    private static $default_sponsor = 'root';
	
	private static $show_sponsor = true;
    
    private static $extensions = array(
        "HierarchyTree"
    );
    
    static function set_root_username($username){
    	Config::inst()->update('Sponsor', 'root_username', $username);
    }
    
    static function get_root_username(){
        return Config::inst()->get('Sponsor', 'root_username');
    }
    
    static function set_default_sponsor($username){
    	Config::inst()->update('Sponsor', 'default_sponsor', $username);
    }
    
    static function get_default_sponsor(){
        return Config::inst()->get('Sponsor', 'default_sponsor');
    }
	
	static function tree_node($id, $show_fields = null){
        $sponsor = DataObject::get_by_id('Sponsor', (int)$id);
        if(!$sponsor) return array();
        
        $result = array();
        $metadata = array();
        $title = '';
        $member = $sponsor->Member();
        
        if(!$show_fields){
            $show_fields = array(
                'ID' => false,
                'Username' => true, 
                'RankTitle' => true, 
                'Status.Title' => true, 
                'JoinedDate.Nice' => true,
                'TotalSponsorDirectDownline.Formatted' => true,
                'TotalSponsorGroupDownline.Formatted' => true
            );
        }
        foreach($show_fields as $show_field => $show){
            if (strstr($show_field, '.')) {
				$parts = explode('.', $show_field);
				$name = array_shift($parts);
				$func = array_shift($parts);
				$obj = $member->obj($name);
				$data = call_user_func(array($obj, $func));
			} else {
				$name = $show_field;
				$data = $member->{$name};
			}
			
			$metadata[$name] = $member->{$name};
			
			if($data == ''){
                $data = 'N/A';
            }

            if($show){
                $title .= "<span class='".$name." tree-title'>".$data."</span>&nbsp";
            }
        }
                    
        $result = array(
            "metadata" => $metadata,
            "attr" => array("id" => "node_".$id, "rel" => $member->RankCode ? strtolower($member->RankCode) : 'unknow'),
            "data" => 
                array(
                    'title' => $title,
                    'icon' => '',
                    'attr' => ''
                ),
            "state" => ($member->TotalSponsorDirectDownline) ? "closed" : ""
        );
        
        return $result;    
    }
    
    static function tree_node_v3($id, $show_fields = null){
        $sponsor = DataObject::get_by_id('Sponsor', (int)$id);
        if(!$sponsor) return array();
        
        $result = array();
        $metadata = array();
        $title = '';
        $member = $sponsor->Member();
        
        if(!$show_fields){
            $show_fields = array(
                'ID' => false,
                'Username' => true, 
                'RankTitle' => true, 
                'Status.Title' => true, 
                'JoinedDate.Nice' => true,
                'TotalSponsorDirectDownline.Formatted' => true,
                'TotalSponsorGroupDownline.Formatted' => true
            );
        }
        foreach($show_fields as $show_field => $show){
            if (strstr($show_field, '.')) {
				$parts = explode('.', $show_field);
				$name = array_shift($parts);
				$func = array_shift($parts);
				$obj = $member->obj($name);
				$data = call_user_func(array($obj, $func));
			} else {
				$name = $show_field;
				$data = $member->{$name};
			}
			
			$metadata[$name] = $member->{$name};
			
			if($data == ''){
                $data = 'N/A';
            }

            if($show){
                $title .= "<span class='".$name." tree-title'>".$data."</span>&nbsp";
            }
        }
                    
        $result = array(
            "id" => "node_" . $id,
            "text" => $title,
            "data" => array(
				"id" => $id,
				"rank" => $member->RankCode
			),
            "children" => ($member->TotalSponsorDirectDownline) ? true : false
        );
        
        return $result;    
    }
    
    function requireDefaultRecords(){
        $root_username = Sponsor::get_root_username();
        if(!$root = DataObject::get_one('Member', "Username = '{$root_username}'")){
            $rootid = Member::create()->setField('Username', $root_username)->write(); 
            $data['Sponsor'] = array(
                'command' => 'insert',
                'fields' => array(
                    'ClassName' => "'Sponsor'",
                    'Created' => "now()",
                    'LastEdited' => "now()",
                    'MemberID' => "'". $rootid ."'",
                    'ParentID' => "'0'"
                )
            );
            DB::manipulate($data);
			$this->create_preorderings();
        }
        else if(!$sponsor = DataObject::get_one('Sponsor', "MemberID = '{$root->ID}'")){
            $data['Sponsor'] = array(
                'command' => 'insert',
                'fields' => array(
                    'ClassName' => "'Sponsor'",
                    'Created' => "now()",
                    'LastEdited' => "now()",
                    'MemberID' => "'". $root->ID ."'",
                    'ParentID' => "'0'"
                )
            );
            DB::manipulate($data);
			$this->create_preorderings();
        }
    }
    
    function setSponsor($username){
    	$this->ParentID = Distributor::get_id_by_username($username);
    }
    
    function onBeforeWrite(){
        if($this->SponsorUsername != ''){
            $this->ParentID = Distributor::get_id_by_username($this->SponsorUsername);
        }
        
        parent::onBeforeWrite();
    }
	
	function onAfterWrite(){
		parent::onAfterWrite();
		if(!$this->isChanged('ID') && $this->isChanged('ParentID')){
			$data = $this->getChangedFields(true);
			ChangeSponsorLog::create()->update(
				array(
					'MemberID' => $this->MemberID,
					'FromSponsorID' => $data['ParentID']['before'],
					'ToSponsorID' => $data['ParentID']['after']
				)
			)->write();
		}
	}
}

?>